#pragma once
#include "mysql.hpp"
#include "friend_apply.hxx"
#include "friend_apply-odb.hxx"

namespace suye
{
class FriendApplyTable {
public:
    using ptr = std::shared_ptr<FriendApplyTable>;
    FriendApplyTable(const std::shared_ptr<odb::core::database>& db): _db(db) {}

    // 新增好友申请事件
    bool insert(FriendApply& ev) 
    {
        try {
            odb::transaction trans(_db->begin());
            _db->persist(ev);
            trans.commit();
        } catch(std::exception &e) {
            LOG_ERROR("新增好友申请事件失败：{}-{}:{}！", ev.user_id(), ev.peer_id(), e.what());
            return false;
        }
        return true;
    }

    // 判断是否存在申请事件
    bool exists(const std::string& uid, const std::string& pid) {
        bool flag = false;
        try {
            odb::transaction trans(_db->begin());
            typedef odb::query<FriendApply> query;
            typedef odb::result<FriendApply> result;
            result r(_db->query<FriendApply>(query::user_id == uid && query::peer_id == pid));
            flag = !r.empty();
            trans.commit();
        }catch (std::exception &e) {
            LOG_ERROR("判断两人好友关系失败:{}-{}-{}！", uid, pid, e.what());
        }
        return flag;
    }

    // 删除好友申请事件
    bool remove(const std::string& uid, const std::string& pid) 
    {
        try {
            odb::transaction trans(_db->begin());
            typedef odb::query<FriendApply> query;
            _db->erase_query<FriendApply>(query::user_id == uid && query::peer_id == pid);
            trans.commit();
        } catch(std::exception& e) {
            LOG_ERROR("删除好友申请事件失败：{}-{}:{}！", uid, pid, e.what());
            return false;
        }
        return true;
    }

    // 获取指定用户的所有申请者用户信息
    std::vector<std::string> applyUsers(const std::string& uid)
    {
        std::vector<std::string> res;
        try {
            odb::transaction trans(_db->begin());
            typedef odb::query<FriendApply> query;
            typedef odb::result<FriendApply> result;
            result r(_db->query<FriendApply>(query::peer_id == uid));
            for (auto it = r.begin(); it != r.end(); ++it) {
                res.push_back(it->user_id());
            }
            trans.commit();
        } catch(std::exception& e) {
             LOG_ERROR("通过用户{}获取的好友申请者失败：{}！", uid, e.what());
        }
        return res;
    }

private:
    std::shared_ptr<odb::core::database> _db;
};
}